package pers.cz.mybatis.slowsql;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.util.Properties;

/**
 * 慢sql检测插件
 * @program: PostGirl-panent
 * @description: SlowSqlPlugin
 * @author: Cheng Zhi
 * @create: 2021-03-13 11:44
 **/
@Intercepts(@Signature(
        type = StatementHandler.class,
        method = "prepare",
        args = { Connection.class, Integer.class }
))
public class SlowSqlPlugin implements Interceptor {
    Logger log = LoggerFactory.getLogger(SlowSqlPlugin.class);
    private long time;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        // 1、通过StatementHandler获取执行的sql
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql();

        long starTime = System.currentTimeMillis();
        Object proceed = invocation.proceed();
        long endTime = System.currentTimeMillis();
        long consumTime = endTime -starTime;
        log.debug("本次查询耗时：" + consumTime);
        if (consumTime > time) {
            log.info("本次数据库操作属于慢查询,共耗时:" + consumTime + "ms, sql: " + sql );
        }
        return proceed;

    }

    @Override
    public void setProperties(Properties properties) {
        this.time = Long.parseLong(properties.getProperty("time"));
    }
}
